<?php

/**
 *   OPENSHOP FTP基类
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: cls_ftp.php,v 1.0 2009/06/17 08:36:58 created $
 *   @author      FillBag <fillbag@hotmail.com>
 */

require_once(ROOT_PATH . 'includes/modules/ftp/ftp_class.php');

class cls_ftp extends ftp {
	
    var $dataList     =  array();
    var $images_dir   =  IMAGE_DIR;
    var $remote_folder =  NULL;
    var $ctype        =  NULL;
    var $is_updata    =  FALSE;
    var $cid;
    
	function cls_ftp($verb=FALSE, $le=FALSE) 
	{
		$this->__construct($verb, $le);
	}

	function __construct($verb=FALSE, $le=FALSE) 
	{
		parent::__construct($verb, $le);
	}

    function connect()
    {
    	global $ftp_host, $ftp_user, $ftp_pass;
		if(!$this->SetServer($ftp_host)) 
		{
			$this->quit();
		}
		
		while (!parent::connect()){
			$this->connect();			
		}
		
		if (!$this->login($ftp_user, $ftp_pass)) 
		{
			$this->quit();
		}    	
    }

	function setting($ctype, $remote_folder=NULL, $auto_mksubdir=TRUE, $subdir_mkrule=NULL){
		if(empty($ctype)) return FALSE;
		$this->ctype = trim($ctype, '|');
        $this->remote_folder =   $remote_folder;	
        $this->auto_mksubdir = $auto_mksubdir;	
        $this->is_updata = FALSE;	
        $this->subdir_mkrule = $subdir_mkrule;	
		return TRUE;
	}
	
	function set_updata($is_updata, $cid=NULL, $ctype=NULL){
	
		if($is_updata==TRUE && !is_numeric($cid)){
			return FALSE;
		}
		$this->is_updata = $is_updata;
	    $this->cid = intval($cid);		
		if($is_updata && $this->drop($cid, $ctype)===FALSE)
			return FALSE;	
		return TRUE;
	}
	
    function put_up($local_res_arr, $remote_folder=NULL, $remote_file=NULL)
    {   
    	if(empty($this->ctype)) return FALSE;
    	if(!is_array($local_res_arr) || empty($local_res_arr['tmp_name']))   return FALSE;
    	if(!is_null($remote_folder))    $this->remote_folder = $remote_folder;   
        $dir = (!is_null($this->subdir_mkrule) && !empty($this->subdir_mkrule)) ? ($this->subdir_mkrule.'/') : (date('Ym') . '/');
        $subdir = $this->auto_mksubdir===TRUE ? $dir : '';
    	if(is_null($this->remote_folder)){
            $remote_folder =  str_replace(SOURCE_DIR.'/', '', $this->images_dir) . '/' . $subdir;
    	}else{
            $remote_folder =  $this->remote_folder . '/' . $subdir;  		
    	}

    	if($this->chdir('/')===FALSE)
    		return FALSE;

        if(!$this->is_exists($remote_folder) && $this->rmkdir($remote_folder)===FALSE)
        {
        	return FALSE;
        }

        if($this->chdir($remote_folder)===FALSE)
        {
        	return FALSE;        	
        } 

        $local_file = $local_res_arr['tmp_name'];     
    	extract($this->set_ctype(), EXTR_OVERWRITE);
		$max_cid = $GLOBALS['db']->getOne("SELECT MAX(pk_id) FROM {$GLOBALS['os']->table('pk_log')} WHERE pk_from='$ctype_name'"); 
		$cid = $this->is_updata==TRUE ? $this->cid : ($max_cid + 1);   
    	if(is_null($remote_file)){
    		if((!$this->file_exists($local_file)) && $sale_oldname==1)
    		{
    			$remote_file = $local_res_arr['name'];
    		}
    		else
    		{
    			$filename = $this->reformat_name($local_res_arr['name'], $this->ctype, $cid);
      			$remote_file = $filename . $this->get_filetype($local_res_arr['name']); 
    		}   
    	}
    	
    	if($this->put($local_file, $remote_file)!==FALSE)
    	{   
    		$width = 0;  $height=0;
    		if($this->check_img_type($local_res_arr['type'])){  
    			 list($width, $height) = $this->get_img_size($local_file);    
    		}
    		return $this->reg(array('ctype'        =>  $serialized_ctype, 
									'affix_name'   =>  $remote_file, 
									'virtual_path' =>  $remote_folder . $remote_file, 
									'cid'          =>  intval($cid),			    		                      
									'width'        =>  $width,
									'height'       =>  $height, 
									'size'         =>  $this->filesize($remote_file),
									'up_time'      =>  gmtime(),
									'enabled'      =>  1));
    	}
    	else
    	{
		 	return FALSE;
    	} 	
    	return FALSE;
    }
    
    function get_xml($remote_file, $in_path=NULL){
        global $file_host;   	
    	if(!is_null($in_path)){    
    	   $this->remote_folder = $in_path;    
       	}
       	
    	if(!is_null($this->remote_folder)){
    	    $remote_file =  $this->remote_folder . "/{$remote_file}";
    	}
    	
    	if($this->chdir('/')==FALSE)  return FALSE;

        if(!$this->file_exists($remote_file)){
        	return FALSE;
        }
    	$realpath = $file_host . '/' . $remote_file;

    	if(FALSE !== file_get_contents($realpath)){   
    		return 	file_get_contents($realpath);	
    	}
    }
    
    function set_xml($xml, $remote_file, $in_path=NULL){
    	if(!is_null($in_path)){    
    	   $this->remote_folder = $in_path;    
       	}
    	if(!is_null($this->remote_folder)){
    	    $remote_file =  $this->remote_folder . "/{$remote_file}";
    	}
    	
    	if($this->chdir('/')==FALSE)  return FALSE;
    	
        if(!$this->is_exists($this->remote_folder) && $this->rmkdir($this->remote_folder)===FALSE)
        {
        	return FALSE;
        }
        
        if(FALSE === $this->drop_file($remote_file, NULL))
            return FALSE;   

    	$fp = fopen("ftp://{$this->_login}:{$this->_password}@{$this->_host}/{$remote_file}","w");    		
    	fwrite ($fp, $xml. "\n");   	
    	fclose ($fp);   
    	return TRUE;
    }
    
    function drop_xml($remote_file, $in_path=NULL){
     	if(!is_null($in_path)){     
     	   $this->remote_folder = $in_path; 
       	}   
    	if(!is_null($this->remote_folder)){
    	    $remote_file =  $this->remote_folder . "/{$remote_file}";
    	}
    	if(FALSE === $this->drop_file($remote_file, NULL))  return FALSE;
    	return TRUE;
    }
    
    function drop($cid, $ctype=NULL){
    	if(!is_null($ctype)) $this->ctype = trim($ctype, '|');
    	if(empty($this->ctype))  return FALSE;
    	
    	if($this->chdir('/')==FALSE)  return FALSE;    
    		
    	extract($this->set_ctype(), EXTR_OVERWRITE);
    	$affix_data = $GLOBALS['db']->getRow("SELECT affix_id,virtual_path FROM " . $GLOBALS['os']->table('affix') . 
    	                                     " WHERE ctype='$serialized_ctype' AND cid=".intval($cid));
    	if(empty($affix_data['virtual_path']))  return FALSE;
    	if(FALSE === $this->drop_file($affix_data['virtual_path'], NULL))  return FALSE;
    	$res = $GLOBALS['db']->query("DELETE FROM " . $GLOBALS['os']->table('affix') . " WHERE affix_id=".intval($affix_data['affix_id']));
    	
    	return TRUE;
    }
    
    function set_ctype(){
     	if(empty($this->ctype)) return FALSE;
    	$item_ctype = strpos($this->ctype, '|') !== FALSE ? explode('|', $this->ctype) : $this->ctype;
    	$c_name = is_array($item_ctype) ? $item_ctype[0] : $item_ctype;
    	$ctype = is_array($item_ctype) ? array('name'=>$item_ctype[0], 'type'=>$item_ctype[1]) : array('name'=>$item_ctype);  

    	return array('ctype_name'=>$c_name, 'serialized_ctype'=> serialize($ctype));
    }
    
    function drop_file($pathname, $in_path=NULL)
    {
    	if(!is_null($in_path)){
    		if(!$this->file_exists($in_path) || $this->chdir($in_path)===FALSE)
            	return FALSE;
    	}

    	if(!$this->is_exists($pathname))
    	{
    		return TRUE;
    	}
    	if(FALSE === $this->delete($pathname)){
    		return FALSE;
    	}
    	return TRUE;
    }
    
    function reg($field_list){
		$temp_field=@implode(",",array_keys($field_list));
		$sql = "INSERT INTO {$GLOBALS['os']->table('affix')} (".$temp_field.") VALUES(";
		$value = ""; 
		foreach ($field_list as $k => $v) 
		{
			if (isset($field_list[$k]))
			{
				if (!get_magic_quotes_gpc())
					$value .= "'".addslashes($field_list[$k])."',";
				else
					$value .= "'".$field_list[$k]."',";
			}	else
				$value .= "'',"; 
		}

		$value = rtrim($value,",");
		$sql .= $value.")"; 
    	$GLOBALS['db']->query($sql);
    	$affix_id = $GLOBALS['db']->insert_id();
    	if($affix_id > 0){
    		return  $this->dataList = array_merge(array('affix_id'=>$affix_id),array_slice($field_list, 0, 4));
    	}
    	return FALSE;        
    }
    
    function get_data(){
    	if(!is_array($this->dataList))
    		return FALSE;
    	return $this->dataList;
    }
    
    function random_filename()
    {
        $str = '';
        for($i = 0; $i < 9; $i++)
        {
            $str .= mt_rand(0, 9);
        }

        return gmtime() . $str;
    }
    
    function reformat_name($file_name, $ctype, $cid)
    {
    	$ext = $this->get_filetype($file_name);
        $filename = '';
        while (empty($filename))
        {
        	$type = strpos($ctype, '|')!==FALSE ? implode('_', explode('|', $ctype)) : $ctype;
            $filename = $cid . '_' . $type . '_' .cls_ftp::random_filename();
            
            if ($this->file_exists($filename . $ext))
            {
                $filename = '';
            }
        }

        return $filename;
    }
    
    function get_filetype($path)
    {
        $pos = strrpos($path, '.');
        if ($pos !== FALSE)
        {
            return substr($path, $pos);
        }
        else
        {
            return '';
        }
    }
    
    function get_img_size($pathname){
		 $item_img = getimagesize($pathname);
         if(!empty($item_img['mime']) && $this->check_img_type($item_img['mime'])){
         	return $item_img;
         }
 	     return FALSE;
    }
   
    function check_img_type($img_type)
    {
        return $img_type == 'image/pjpeg' ||
               $img_type == 'image/x-png' ||
               $img_type == 'image/png'   ||
               $img_type == 'image/gif'   ||
               $img_type == 'image/jpeg';
    }
    
    function rmkdir($pathname){
    	$arr_path = array();
    	$arr_path = explode('/', str_replace('//','/',trim($pathname, '/')));
    	if($this->chdir('/')===FALSE)
    		return FALSE;
 
    	foreach($arr_path as $path){
    		if(!empty($path)){
		        if(!$this->file_exists($path) && $this->mkdir($path)===FALSE)
		        {
		        	return FALSE;
		        }
		        if($this->chdir($path)==FALSE)
		        {
		        	return FALSE;        	
		        } 
    		}
    	}
    	
    	if($this->chdir('/')===FALSE)
    		return FALSE;
    		
    	return TRUE;
    }
    
//	function hash_call($ctypeName,$ftpStr)	{
//
//		global $ftp_host, $ftp_pass, $ftp_user;
//		$ch = curl_init();
//		curl_setopt($ch, CURLOPT_URL, $this->api_url);
//		curl_setopt($ch, CURLOPT_VERBOSE, 1);
//	
//		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
//		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
//	
//		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//		curl_setopt($ch, CURLOPT_POST, 1);
//
//		if(USE_PROXY)
//		curl_setopt ($ch, CURLOPT_PROXY, PROXY_HOST.":".PROXY_PORT); 
//	
//		$ftpreq="CTYPE=".urlencode($ctypeName)."&PWD=".urlencode($this->_passwd)."&USER=".urlencode($this->_user).$ftpStr;
//		
//		curl_setopt($ch,CURLOPT_POSTFIELDS,$ftpreq);
//	
//		$response = curl_exec($ch);
//	
//		$ftpResArray=$this->deformatFTP($response);
//		$ftpReqArray=$this->deformatFTP($ftpreq);
//		$_SESSION['ftpReqArray']=$ftpReqArray;
//	
//		if (curl_errno($ch)) {
//			  $_SESSION['curl_error_no']=curl_errno($ch) ;
//			  $_SESSION['curl_error_msg']=curl_error($ch);
//			  $location = "APIFTPError.php";
//			  header("Location: $location");
//		} else {
//			  curl_close($ch);
//	    }
//	
//	    return $ftpResArray;
//	}

//	function deformatFTP($ftpstr)
//	{
//		$intial=0;
//	 	$ftpArray = array();
//	
//	
//		while(strlen($ftpstr)){
//			$keypos= strpos($ftpstr,'=');
//			$valuepos = strpos($ftpstr,'&') ? strpos($ftpstr,'&'): strlen($ftpstr);
//	
//			$keyval=substr($ftpstr,$intial,$keypos);
//			$valval=substr($ftpstr,$keypos+1,$valuepos-$keypos-1);
//
//			$nvpArray[urldecode($keyval)] =urldecode( $valval);
//			$ftpstr=substr($ftpstr,$valuepos+1,strlen($ftpstr));
//	     }
//		return $ftpArray;
//	}
}
?>